package com.aaa.auth.service;

import com.aaa.auth.feign.SystemFeign;
import com.aaa.common.entity.AclPermission;
import com.aaa.common.entity.AclUser;
import com.aaa.common.vo.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
@Service
public class MyUserService implements UserDetailsService {

    @Autowired
    private SystemFeign systemFeign;

    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
        //根据账户查询用户信息
        Result<AclUser> result = systemFeign.getByName(s);
        if (result!=null&&result.getData()!=null){
            AclUser aclUser = result.getData();

            Result<List<AclPermission>> result1 = systemFeign.getByUserid(aclUser.getId());
            if(result1!=null){
                List<AclPermission> permissions = result1.getData();
            List<SimpleGrantedAuthority>authorities=permissions.stream().
                    filter(item->item.getPermissionValue()!=null)
                    //过滤掉不满足条件的元素
                    .map(item->new SimpleGrantedAuthority(item.getPermissionValue()))
                    .collect(Collectors.toList());
            User user = new User(aclUser.getUsername(), aclUser.getPassword(),authorities);
            return user;
            }

        }
        return null;
    }
}
